package org.shiro.demo.disruptor;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.shiro.demo.entity.MPWeixinToken;
import org.shiro.demo.service.IMPWeixinTokenService;
import org.shiro.demo.util.WeixinPayClient;

import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.WorkHandler;

/*
 * 见文档https://mp.weixin.qq.com/advanced/tmplmsg?action=faq&token=1824682281&lang=zh_CN
 */
public class TradeTransactionInWXHandler implements EventHandler<TradeTransaction>, WorkHandler<TradeTransaction> {

	private IMPWeixinTokenService weixinTokenService;

	public IMPWeixinTokenService getWeixinTokenService() {
		return weixinTokenService;
	}

	public void setWeixinTokenService(IMPWeixinTokenService weixinTokenService) {
		this.weixinTokenService = weixinTokenService;
	}

	@Override
	public void onEvent(TradeTransaction event, long sequence, boolean endOfBatch) throws Exception {
		this.onEvent(event);
	}

	private static DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Override
	public void onEvent(TradeTransaction event) throws Exception {
		// 这里做具体的消费逻辑
		event.setId(UUID.randomUUID().toString());// 简单生成下ID
		System.out.println("id:" + event.getId() + "---------price:" + event.getPrice() + "---------content:" + event.getContent());
		// 发送微信 。。判断是否过期了。
		MPWeixinToken weixintoken = weixinTokenService.get(1);

		if (weixintoken.getExpires_time().before(new Date())) {// token
																// 早于当前时间，说明消逝了
			// 更新token
			weixintoken = weixinTokenService.update(1);
		}
		// 有可能 token 还是 失效了。？
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + weixintoken.getAccess_token();

		WeixinPayClient client = new WeixinPayClient(url);
		boolean die = false;
		for (String openid : event.getOpenids()) {
			// 不管是否成功了
			String ret = client.post(conStr(event.getUrl(),openid, "顾客有一笔订单已经生成，请准备提货。", format.format(event.getCreateTime()), event.getContent(), "x盒", event.getPrice() + "", "有疑问联系152"));
			System.out.println("返回" + ret);
			// 失效 返回{"errcode":42001,"errmsg":"access_token expired"}
			// 成功 返回 {"errcode":0,"errmsg":"ok","msgid":207067765}
			JSONObject jsonObj = JSONObject.fromObject(ret);
			if (((Integer) jsonObj.get("errcode")) != 0) {// 未成功,说明 失效再来。
				// 更新
				die = true;
				break;
			}
		}
		if (die) {
			weixintoken = weixinTokenService.update(1);
			url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + weixintoken.getAccess_token();
			client = new WeixinPayClient(url);
			for (String openid : event.getOpenids()) {
				// 不管是否成功了
				String ret = client.post(conStr(event.getUrl(),openid, "顾客有一笔订单已经生成，请准备提货。", format.format(event.getCreateTime()), event.getContent(), "x盒", event.getPrice() + "", "有疑问联系152"));
				System.out.println("返回" + ret);
			}
		}
	}

	private static String conStr(String url, String openid, String first, String keyword1, String keyword2, String keyword3, String keyword4, String remark) {
		StringBuilder sb = new StringBuilder();

		sb.append("{\"touser\":\"" + openid + "\",\"template_id\":\"5J2Z5OqyCzv7gdtu0R1NsCucRaGYFuByh9REOpFn9I4\",\"url\":\""+url+"\",\"topcolor\":\"#FF0000\",\"data\":{");

		sb.append("\"first\": {\"value\":\"" + first + "\",\"color\":\"#173177\"},\"keyword1\":{\"value\":\"" + keyword1 + "\",\"color\":\"#173177\"},\"keyword2\":{\"value\":\"" + keyword2 + "\",\"color\":\"#173177\"},\"keyword3\":{\"value\":\"" + keyword3 + "\",\"color\":\"#173177\"},\"keyword4\":{\"value\":\"" + keyword4 + "\",\"color\":\"#173177\"},\"remark\":{\"value\":\"" + remark + "\",\"color\":\"#173177\"}}}");
		return sb.toString();
	}

	public static void main(String[] args) throws Exception {
		// 发送微信
		// String url =
		// "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
		// + TokenAccess.GetExistAccessToken();
		// WeixinPayClient client = new WeixinPayClient(url);
		// System.out.println(conStr());
		// String retu = client.post(conStr());
		// System.out.println(retu);

	}
}
